<template>
    <el-form v-loading="loading" :model="form" label-width="120px">
        <el-form-item label="课程 名称">
            <el-input :disabled="readOnly" v-model="form.courseName" />
        </el-form-item>
        <el-form-item label="课程 标签">
            <el-select :disabled="readOnly" v-model="selectList" multiple collapse-tags collapse-tags-tooltip placeholder="Select"
                style="width: 240px">
                <el-option-group v-for="one in courseTagList" style="color:red;" :key="one.courseTagId"
                    :label="'———— ' + one.courseTagName + ' ————'">
                    <el-option-group v-for="two in one.tagList" :key="two.courseTagId" :label="two.courseTagName">
                        <el-option v-for="item in two.tagList" :key="item.courseTagId" :label="item.courseTagName"
                            :value="item.courseTagId" />
                    </el-option-group>

                </el-option-group>

            </el-select>
        </el-form-item>
        <el-form-item label="课程 封面">
            <el-upload class="upload-demo" action="" :limit="1" :on-exceed="onExceed" :on-remove="fileRemove"
                :on-change="fileChange" :auto-upload="false">
                <template #trigger>
                    <el-button :disabled="readOnly" type="primary">选择 图片</el-button>
                </template>

                <template #tip>
                    <div class="el-upload__tip">
                        请上传 jpg/png 文件 , 5MB
                    </div>
                </template>
            </el-upload>

        </el-form-item>

        <el-form-item label="课程 售价">
            <el-input-number :disabled="readOnly" :min="0.00" v-model="form.price" :precision="2" :step="1" :max="10" />
        </el-form-item>

        <el-form-item label="课程 简述">
            <el-input :disabled="readOnly" v-model="form.description" type="textarea" />
        </el-form-item>
        <el-form-item v-if="!isCreate">
            <el-button type="primary" @click="onSubmit()">创 建</el-button>
            <el-button @click="clear()">清 空</el-button>
        </el-form-item>
    </el-form>


</template>

<script>
import { reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Plus, ZoomIn } from '@element-plus/icons-vue'
export default {
    name: 'createCourse',
    components: { Delete, Plus, ZoomIn },
    props: ['courseTagList', 'courseId'],
    setup(props) {
        const form = reactive({
            courseName: '',
            price: 0.00,
            description: '',
            url: ''
        })
        //选择的图片文件
        const imgFile = null;
        //选择的标签集合
        const selectList = ref([]);
        //获取到的标签集合
        //[{ courseTagId: 1, courseTagName: '一级标签1', courseTagParentId: null, courseTagStatus: 1, tagList: [{ courseTagId: 2, courseTagName: '二级标签1', courseTagParentId: 1, courseTagStatus: 1, tagList: [{ courseTagId: 3, courseTagName: '三级标签1', courseTagParentId: 2, courseTagStatus: 1 }] },] },]
        const courseTagList = props.courseTagList;
        //是否开启加载
        const loading = false;
        //是否只读
        const readOnly = ref(false);
        //是否上传
        const isCreate = ref(false);

        return { form, imgFile, selectList, courseTagList, loading,readOnly,isCreate };
    },
    methods: {
        clear() {
            this.form.courseName = "";
            this.form.price = 0.00;
            this.form.description = "";
            this.form.url = "";
            this.imgFile = null;
            this.selectList = [];
        },
        onSubmit() {
            let flag = false;
            //检查是否选择课程封面
            if (this.imgFile == null) {
                ElMessageBox.confirm('当前未选择课程封面，是否使用默认图片？').then(() => { this.createCourse() })
            } else {
                this.createCourse()
            }
        },
        createCourse() {
            //检查课程名称是否为空
            if (this.form.courseName == null || this.form.courseName == '') {
                ElMessage.warning('课程名称不能为空');
                return;
            }
            //检查课程标签大小是否小于等于0
            if (this.selectList == null || this.selectList.length == 0) {
                ElMessage.warning('课程标签不能为空');
                return;
            }
            //检查文件是否为空,不为空则进行文件上传
            if (null != this.imgFile) {
              //开启加载
              this.loading = true;
                //上传文件，获取文件路径
                //将图片文件添加到fromData对象中
                let formData = new FormData();
                formData.append("courseImgFile", this.imgFile.raw);
                formData.append("oldFilePath","");
                let config = {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                }
                let w = '/api/uploadCourseImg';
                this.axios.post(w, formData, config).then((fileRes) => {
                    if (fileRes.data.code == 200) {
                        //将文件路径存放到对象的属性中
                        this.form.url = fileRes.data.data;
                        console.log(fileRes.data.data)
                        //创建课程信息
                        this.axios.post("/api/createCourse", {
                            courseName: this.form.courseName,
                            courseDescription: this.form.description,
                            courseCoverPath: this.form.url,
                            coursePrice: this.form.price
                        }).then((courseRes) => {
                          if (courseRes.data.code == 200) {
                            //将数据存放到formData中
                            let formData = new FormData();
                            formData.append("selectList", this.selectList);
                            formData.append("courseId", courseRes.data.data);
                            //添加课程标签
                            this.axios.post("/api/insertCourseType", formData, {
                              headers: {
                                'Content-Type': 'multipart/form-data'
                              }
                            }).then((typeRes) => {
                              if (typeRes.data.code == 200) {
                                ElMessage.success('创建成功');
                                //将上传按钮隐藏，所有文本不可编辑
                                this.readOnly = true;
                                this.isCreate = true;

                              }else {
                                ElMessage.warning(typeRes.data.msg)
                              }
                            }).catch(function (error) {
                              console.log(error)
                            });
                          }else {
                            ElMessage.warning(courseRes.data.msg);
                          }
                        }).catch(function (error) {
                            console.log(error)
                        });
                    } else {
                        ElMessage.warning(fileRes.data.msg);
                    }

                }).catch(function (error) {
                    console.log(error)
                }).finally(()=>{
                  //关闭加载
                  this.loading = false;
                });
            }


        },
        fileChange(uploadFile, uploadFiles) {
            //检查文件是否是jpg和png格式
            if (uploadFile.raw.type == "image/jpeg" || uploadFile.raw.type == "image/png") {
                //检查上传文件大小是否
                //存放该文件到对象中
                this.imgFile = uploadFile;
                console.log(uploadFile);
            } else {
                ElMessage.warning(
                    `上传文件应为jpg/png格式`
                )
            }

        },
        fileRemove(uploadFile, uploadFiles) {
            //当删除文件时，将本地的文件对象清空
            this.imgFile = null;
        },
        onExceed(uploadFiles) {
            //当文件超出限制时
            ElMessage.warning(
                `只能选择一张图片作为视频封面`
            )
        }
    }

}
</script>

<style>
</style>